//
//  UIImage+Extensions.swift
//  status
//
//  Created by 彳亍 on 2017/3/23.
//  Copyright © 2017年 彳亍. All rights reserved.
//

import UIKit


// MARK: - 绘制图片
extension UIImage {

    /// 裁剪,绘制图片
    ///
    /// - Parameters:
    ///   - size: 目标大小
    ///   - backgroundColor: 背景色
    ///   - borderColor: 边缘颜色
    ///   - opaque: 不透明度
    /// - Returns: 绘制结果
    func ch_clipImage(size:CGSize?,backgroundColor:UIColor?,borderColor:UIColor?,opaque:Bool = true) -> UIImage? {
 
        var size = size
        if size == nil {
            size = self.size
        }
        
        let rect = CGRect(origin: CGPoint(), size: size!)
        // 开启图片上下文
        UIGraphicsBeginImageContextWithOptions(rect.size, opaque, 0)
        
        if let backgroundColor = backgroundColor {
            backgroundColor.setFill()
            UIRectFill(rect)
        }
        // 裁剪
        let path = UIBezierPath(ovalIn: rect)
        path.addClip()
        // 绘制
        draw(in: rect)
        // 设置边缘
        if let borderColor = borderColor {
            let ovalPath = UIBezierPath(ovalIn: rect)
            borderColor.setStroke()
            ovalPath.lineWidth = 2
            ovalPath.stroke()
        }
        // 获取绘制结果
        let resoult = UIGraphicsGetImageFromCurrentImageContext()
        // 关闭上下文
        UIGraphicsEndImageContext()
        // 返回结果
        return resoult
    }
    
}
